package com.rocket.demo1;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class Consumer {
    public static void main(String[] args) throws MQClientException {
        /*
        标识一类Consumer的集合名称，

        这类Consumer通常消费一类消息，且消费逻辑一致。
        同一个Consumer Group下的各个实例将共同消费
        topic的消息，起到负载均衡的作用。

        消费进度以Consumer Group为粒度管理，不同
        Consumer Group之间消费进度彼此不受影响，
        即消息A被Consumer Group1消费过，也会再
        给Consumer Group2消费。

        注： RocketMQ要求同一个Consumer Group的
        消费者必须要拥有相同的注册信息，即必须要听一样
        的topic(并且tag也一样)。
         */
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("rocket-consumer");
        //consumer.setNamesrvAddr("192.168.64.151:9876:192.168.64.152:9876");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.subscribe("topic-demo1", "tag-a");//多个标签用这样的形式"TagA || TagB || TagC"
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt strExt : list) {
                    String msg = new String(strExt.getBody());
                    System.out.println("对应的消息队列是: " + strExt.getQueueId());
                    System.out.println(msg);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
        System.out.println("开始消费信息!");
    }
}
